package cn.ss.exam2302.service.impl;

import cn.ss.exam2302.entity.*;
import cn.ss.exam2302.mapper.*;
import cn.ss.exam2302.service.PaperService;
import cn.ss.exam2302.util.EncryptUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PaperServiceImpl implements PaperService {
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private SingleMapper singleMapper;
    @Autowired
    private YesnoMapper yesnoMapper;
    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Override
    public JsonResult query(Integer paId, String paPassword) {
        Paper paper = paperMapper.selectById(paId);
        if (paper == null) return new JsonResult(JsonResult.FAIL, "卷ID不存在");
        if (!paPassword.equals(paper.getPaPassword())) return new JsonResult(JsonResult.FAIL, "密码不正确");
        Boolean paStatus = paper.getPaStatus();
        if (paStatus == null)  return new JsonResult(JsonResult.FAIL, "题库缺失");
        if (paStatus)  return new JsonResult(JsonResult.FAIL, "未开放");
        QueryWrapper<Single> singleQueryWrapper = new QueryWrapper<>();
        singleQueryWrapper.eq("sin_pa_id", paId);
        Integer singleCount = singleMapper.selectCount(singleQueryWrapper);
        QueryWrapper<Yesno> yesnoQueryWrapper = new QueryWrapper<>();
        yesnoQueryWrapper.eq("yn_pa_id", paId);
        Integer yesnoCount = yesnoMapper.selectCount(yesnoQueryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("paName", paper.getPaName());
        data.put("singleCount", singleCount);
        data.put("yesnoCount", yesnoCount);
        return new JsonResult(JsonResult.SUCCESS, null, data);
    }

    @Override
    public void hand(Integer paId) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getUsrId();
        QueryWrapper<Answer> answerQueryWrapper = new QueryWrapper<>();
        answerQueryWrapper.eq("ans_usr_id", userId);
        answerQueryWrapper.eq("ans_pa_id", paId);
        List<Answer> answerList = answerMapper.selectList(answerQueryWrapper);
        int mark = 0;
        for (Answer answer : answerList) {
            QueryWrapper<Single> singleQueryWrapper = new QueryWrapper<>();
            singleQueryWrapper.eq("sin_pa_id", paId);
            singleQueryWrapper.eq("sin_pos", answer.getAnsPos());
            Single single = singleMapper.selectOne(singleQueryWrapper);
            if (single != null){
                if (single.getSinStandard() == answer.getAnsSelect()) mark += single.getSinPower();
                continue;
            }
            QueryWrapper<Yesno> yesnoQueryWrapper = new QueryWrapper<>();
            yesnoQueryWrapper.eq("yn_pa_id", paId);
            yesnoQueryWrapper.eq("yn_pos", answer.getAnsPos());
            Yesno yesno = yesnoMapper.selectOne(yesnoQueryWrapper);
            if (yesno != null){
                if (yesno.getYnStandard() == answer.getAnsSelect()) mark += yesno.getYnPower();
            }
        }
        QueryWrapper<Score> scoreQueryWrapper = new QueryWrapper<>();
        scoreQueryWrapper.eq("sc_usr_id", userId);
        scoreQueryWrapper.eq("sc_pa_id", paId);
        Score score = scoreMapper.selectOne(scoreQueryWrapper);
        if (score != null){
            score.setScMark(mark);
            score.setScUpdatedate(new Date());
            scoreMapper.updateById(score);
            return;
        }
        score = new Score();
        score.setScId(EncryptUtil.randUUID());
        score.setScPaId(paId);
        score.setScUsrId(userId);
        score.setScMark(mark);
        score.setScCreatedate(new Date());
        scoreMapper.insert(score);
    }

    @Override
    public List<Score> score() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getUsrId();
        return scoreMapper.selectAll(userId);
    }

    @Override
    public JsonResult add(Paper paper) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getUsrId();
        paper.setPaUsrId(userId);
        paper.setPaCreatedate(new Date());
        return paperMapper.insert(paper) == 1 ? JsonResult.JSONRESULT_SUCCESS : JsonResult.JSONRESULT_FAIL;
    }

    @Override
    public List<Paper> queryAll() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getUsrId();
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pa_usr_id", userId);
        return paperMapper.selectList(queryWrapper);
    }

    @Override
    public JsonResult upload(MultipartFile file, Integer paId) throws IOException {
        //先删除题库
        QueryWrapper<Single> singleQueryWrapper = new QueryWrapper<>();
        singleQueryWrapper.eq("sin_pa_id", paId);
        singleMapper.delete(singleQueryWrapper);
        QueryWrapper<Yesno> yesnoQueryWrapper = new QueryWrapper<>();
        yesnoQueryWrapper.eq("yn_pa_id", paId);
        yesnoMapper.delete(yesnoQueryWrapper);
        //利用poi解析excel文件
        String filename = file.getOriginalFilename();
        Workbook workbook;
        if (filename.endsWith(".xls")){
            workbook = new HSSFWorkbook(file.getInputStream());
        } else {
            workbook = new XSSFWorkbook(file.getInputStream());
        }
        Sheet sheet = workbook.getSheetAt(0);
        for (Row row : sheet) {
            String type = row.getCell(0).toString();
            if (type.equals("单选")){
                Integer pos = ((Double) Double.parseDouble(row.getCell(1).toString())).intValue();
                String caption = row.getCell(2).toString();
                String a = row.getCell(3).toString();
                String b = row.getCell(4).toString();
                String c = row.getCell(5).toString();
                String d = row.getCell(6).toString();
                Character standard = row.getCell(7).toString().charAt(0);
                Integer power = ((Double)Double.parseDouble(row.getCell(8).toString())).intValue();
                Single single = new Single(EncryptUtil.randUUID(), pos, caption, a, b, c, d, standard, power, paId, new Date(), null);
                singleMapper.insert(single);
            } else if (type.equals("判断")){
                Integer pos = ((Double) Double.parseDouble(row.getCell(1).toString())).intValue();
                String caption = row.getCell(2).toString();
                Character standard = row.getCell(7).toString().charAt(0);
                Integer power = ((Double)Double.parseDouble(row.getCell(8).toString())).intValue();
                Yesno yesno = new Yesno(EncryptUtil.randUUID(), pos, caption, standard, power, paId, new Date(), null);
                yesnoMapper.insert(yesno);
            }
        }
        //更新题库状态
        Paper paper = paperMapper.selectById(paId);
        if (paper.getPaStatus() == null){
            paper.setPaStatus(false);
            paperMapper.updateById(paper);
        }
        return JsonResult.JSONRESULT_SUCCESS;
    }

    @Override
    public JsonResult setStatus(String status, Integer paId) {
        Boolean paStatus = status.equals("关闭") ? false : true;
        Paper paper = new Paper();
        paper.setPaStatus(paStatus);
        paper.setPaId(paId);
        paperMapper.updateById(paper);//部分更新
        return JsonResult.JSONRESULT_SUCCESS;
    }

    @Override
    public JsonResult setPassword(String password, Integer paId) {
        Paper paper = new Paper();
        paper.setPaPassword(password);
        paper.setPaId(paId);
        paperMapper.updateById(paper);//部分更新
        return JsonResult.JSONRESULT_SUCCESS;
    }
}
